package com.wyy.service.impl;

import com.alibaba.fastjson.JSON;
import com.wyy.error.BusinessException;
import com.wyy.error.EnumBusinessError;
import com.wyy.mapper.UsersMapper;
import com.wyy.pojo.Users;
import com.wyy.pojo.model.UserToken;
import com.wyy.service.UsersService;
import com.wyy.util.MyUtil;
import com.wyy.util.TokenUtils;
import lombok.SneakyThrows;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: gytcb
 * @author: 吴磊
 * @create: 2021-06-02 11:03
 */
@Service
public class UsersServiceImpl implements UsersService {
    @Autowired
    private UsersMapper usersMapper;


    @Autowired
    private TokenUtils tokenUtils;

    private MyUtil myUtil = new MyUtil();


    /**
     * 根据用户名称模糊查询用户
     *
     * @param userToken
     * @return
     */
    @Override
    public Map<String, Object> getUserByNameLike(UserToken userToken) {
        String userNickname = userToken.getUserNickname();
        userNickname = "%" + userNickname + "%";
        userToken.setUserNickname(userNickname);
        List<UserToken> userByNameLike = usersMapper.getUserByNameLike(userToken);
        Integer count = usersMapper.getCountByNameLike(userToken);
        HashMap<String, Object> map = new HashMap<>();
        map.put("users", userByNameLike);
        map.put("total", count);
        return map;
    }

    @Override
    public Map<String, Object> getAllUsers() {
        Map<String, Object> map = new HashMap<>();
        map.put("allUser", usersMapper.getAllUsers());
        return map;
    }

    @SneakyThrows
    @Override
    public Map<String, Object> login(String userNickName, String userPassword) {
        if (StringUtils.isEmpty(userNickName) || StringUtils.isEmpty(userPassword)) {
            throw new BusinessException(EnumBusinessError.PARAMETER_INVALID_ERROR);
        }
        Users loginUser = usersMapper.getUserByUserNicknameAndPwd(userNickName, userPassword);
        Map<String, Object> map = new HashMap<>();
        if (StringUtils.isEmpty(loginUser)) {
            throw new BusinessException(EnumBusinessError.USER_NOT_LOGIN, "用户名或密码错误");
        } else {
            map.put("userRole", loginUser.getUserRole());
            //生成当前用户专有Token
            UserToken userToken = new UserToken();
            BeanUtils.copyProperties(loginUser, userToken);
            String token = tokenUtils.generateToken(userToken);

            //然后存到redis，并设置时间为1天
            tokenUtils.storageToken(token, userNickName);
            UserToken info = tokenUtils.getInfoFromToken(token);
            map.put("token", token);
            map.put("login", "success");
            map.put("login_user", info);
            return map;
        }
    }

    @Override
    public Map<String, Object> getUserByUserNickname(String userNickname) {
        Users user = usersMapper.getUserByUserNickname(JSON.parseObject(userNickname, Users.class).getUserNickname());
        Map<String, Object> map = new HashMap<>();
        if (StringUtils.isEmpty(user)) {
            map.put("verify", "success");
        } else {
            throw new BusinessException(EnumBusinessError.USER_NICKNAME_IS_EXIST);
        }
        return map;
    }

    @Override
    public Map<String, Object> getUserByUserEmail(String userEmail) {
        Users user = usersMapper.getUserByUserEmail(JSON.parseObject(userEmail, Users.class).getUserEmail());
        Map<String, Object> map = new HashMap<>();
        if (StringUtils.isEmpty(user)) {
            map.put("verify", "success");
        } else {
            throw new BusinessException(EnumBusinessError.EMAIL_IS_EXIST);
        }
        return map;
    }

    @Override
    public Map<String, Object> register(Users users) {
        String id = myUtil.getUUID();
        users.setUserId(id);
        String detailedTime = myUtil.getCurrentDetailedTime();
        users.setUserRegistrationTime(detailedTime);
        Integer i = usersMapper.insertUser(users);
        if (i <= 0) {
            throw new BusinessException(EnumBusinessError.UNKNOWN_ERROR, "注册失败");
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("register", "success");
        return map;
    }

    @Override
    public Map<String, Object> updateUser(Users users) {
        Integer i = usersMapper.updateUser(users);
        if (i <= 0) {
            throw new BusinessException(EnumBusinessError.UNKNOWN_ERROR, "更新数据失败");
        }
        return null;
    }

    @Override
    public Map<String, Object> userPasswordIsOK(String password) {
        //获取用户传过来的密码
        String userPassword = JSON.parseObject(password, Users.class).getUserPassword();

        UserToken token = tokenUtils.parseTokenToUserToken();
        Users user = usersMapper.getUserById(token.getUserId());
        //得到用户原来的密码
        String userUserPassword = user.getUserPassword();
        HashMap<String, Object> map = new HashMap<>();
        if (userUserPassword.equals(userPassword)) {
            map.put("isOk", true);
        } else {
            map.put("isOk", false);
        }
        return map;
    }

    @Override
    public Map<String, Object> getUserById(String userId) {
        String id = JSON.parseObject(userId, Users.class).getUserId();
        Users user = usersMapper.getUserById(id);
        user.setUserPassword("");
        user.setUserRole("");
        HashMap<String, Object> map = new HashMap<>();
        map.put("user", user);
        return map;
    }
}